package projects

import (
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"xpms/app/models"
	"xpms/cores/utils"
)

type ProjectsPlan struct {
	Id              int64 `orm:"pk;column(planid);" json:"Id,string"`
	Projectid       int64 `json:"Projectid,string"`
	Title           string
	Vesionno        string
	Started         int64
	Ended           int64
	Actualstarttime int64
	Actualendtime   int64
	Content         string
	Parentplanid    int64 `json:"Parentplanid,string"`
	Created         int64
	Createid        int64 `json:"Createid,string"`
	Status          int
	Changed         int64
	Swimlanesid     int64
}

type ProjectsPlanDto struct {
	Id              int64 `json:"Id,string"`
	Projectid       int64 `json:"Projectid,string"`
	Projectname     string
	Title           string
	Vesionno        string
	Started         int64
	Ended           int64
	Actualstarttime int64
	Actualendtime   int64
	Content         string
	Parentplanid    int64 `json:"Parentplanid,string"`
	Created         int64
	Createid        int64 `json:"Createid,string"`
	Createname      string
	Status          int
	Changed         int64
	Swimlanesid     int64 `json:"Swimlanesid,string"`
}

func (this *ProjectsPlan) TableName() string {
	return models.TableName("projects_plan")
}

func init() {
	orm.RegisterModel(new(ProjectsPlan))
}

func AddPlan(upd ProjectsPlan) error {
	o := orm.NewOrm()
	needs := new(ProjectsPlan)

	needs.Id = upd.Id
	needs.Projectid = upd.Projectid
	utils.SimpleCopyProperties(needs, upd)
	needs.Created = time.Now().Unix()
	_, err := o.Insert(needs)
	return err
}

func UpdatePlan(id int64, upd ProjectsPlan) error {
	needs := new(ProjectsPlan)
	o := orm.NewOrm()
	//needs = ProjectsPlan{Id: id}
	needs.Id = id
	utils.SimpleCopyProperties(needs, upd)
	needs.Changed = time.Now().Unix()
	_, err := o.Update(needs)
	return err

}

func GetPlan(id int64) (ProjectsPlan, error) {
	var needs ProjectsPlan
	var err error
	o := orm.NewOrm()
	needs = ProjectsPlan{Id: id}
	err = o.Read(&needs)

	if err == orm.ErrNoRows {
		return needs, nil
	}
	return needs, err
}
func ChangePlanStatus(id int64, userid int64, status int) error {
	o := orm.NewOrm()
	plan, err := GetPlan(id)
	if nil != err {
		return err
	} else {
		plan.Status = status
		if 2 == status {
			plan.Actualstarttime = time.Now().Unix()
			plan.Actualendtime = 0
		} else if 3 == status || 5 == status {
			plan.Actualendtime = time.Now().Unix()
		}
		plan.Changed = time.Now().Unix()
		_, err := o.Update(&plan)
		return err
	}
}

func PlanPageExec(condArr map[string]interface{}, page int, offset int) (ops []ProjectsPlanDto) {
	o := orm.NewOrm()
	var dto []ProjectsPlanDto
	o.Raw(planPageSql(condArr, 1, page, offset)).QueryRows(&dto)
	return dto
}

func PlanPageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var Dto int64
	o.Raw(planPageSql(condArr, 0, page, offset)).QueryRow(&Dto)
	return Dto
}

/**
  组装sql
*/
func planPageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT
	    plan.*,
	    plan.planid AS id,
		users.realname AS createname,
	  pp.name AS projectname
	FROM  pms_projects pp INNER JOIN pms_projects_plan plan ON plan.projectid=pp.projectid
	LEFT JOIN pms_users_profile users ON users.userid=plan.createid
	WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["projectid"]) {
		sql = sql + ` and  plan.projectid=?`
		param = append(param, condArr["projectid"])
	}
	if !utils.IsEmpty(condArr["keyword"]) {
		sql = sql + ` and  plan.Title LIKE concat('%',?,'%')`
		param = append(param, condArr["keyword"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by created desc LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}
